#!/usr/bin/env python
#-*-encoding:utf-8-*-
'''
Created on 2015年11月4日

@author: chenyongbing
'''
import sys,os,datetime,md5,inspect
#current_dir = os.path.dirname(__file__)
current_dir = os.path.split(os.path.realpath(__file__))[0]
import logging,json,urllib,urllib2,time,re
    
class VerifyZhimindWSV4Data():
    def __init__(self,base='http://open.zhimatech.com/api/v3/zhimind/',version='v3'):
#         self.app_key = 'gaodadezhimatechwoaizhimamofi200'
#         self.secret_key = 'gaodadezhimatechwoaizhimamofi200'
        self.app_key = 'e35f6068391eb3d0747294fc425971cc'
        self.secret_key = '105f5649981c40b9545e86f1df29c43e'

        
        self.day = datetime.date.today().strftime('%Y-%m-%d')
        self.time = int(datetime.datetime.today().strftime('%s'))*1000
        if version == 'v3':
            self.token = 10002000
        else:
            self.token = md5.new(self.app_key+str(self.time)+self.secret_key).hexdigest()
        self.base = base
        
        
        
    def getResponse(self,url,detailMap={},data=None,type='post'):
        if 'Token' not in detailMap.keys():
            detailMap['Token'] = self.token
        if 'Key' not in detailMap.keys():
            detailMap['Key'] = self.app_key

        if 'Timestamp' not in detailMap.keys():
            detailMap['Timestamp'] = self.time
            #'token':self.token,'key':self.app_key,'day':self.day,'time':self.time
        if data==None:
            groupList = []
            listKeys = []
            for key,values in detailMap.iteritems():
                if isinstance(values,list):
                    listKeys.append(key)
                    
                    #del detailMap[key]
            for lk in listKeys:
                values = detailMap[lk]
                del detailMap[lk]
                count = 0
                for value in values:
                    count+=1
                    detailMap[lk+'_'+str(count)] = value
            
            data=urllib.urlencode(detailMap)
            for lk in listKeys:
                data = re.sub('%s_[\d]+'%lk,lk,data)
            
        else:
            data = data
        st = time.time()
        if type=='post':
            logging.info( url+"   "+data)
            req=urllib2.Request(url,data)
#             print req
            response=urllib2.urlopen(req)
        else:
            logging.info( url+'?'+data)
            response = urllib2.urlopen(url+'?'+data)
            
        page=response.read()
        et = time.time()
        logging.info( 'use time:%s'%(et-st))
        #print "page",page
        return json.loads(page)

        
    def get_params_from_method(self,argvalues):
        keys = argvalues.args
        keys.remove('self')
        locals = argvalues.locals
        
        datas = {}
        
        for k,v in locals.items():
            if k in keys:
                nk = re.sub('^%s'%k[0],k[0].upper(),k)
                if nk=='TimeType':
                    if v == 'day':v=1
                    if v == 'week':v=2
                    if v == 'month':v=3
                datas[nk] = v
                
        return datas
    
    
    
    
    def entered_customer_count(self,startTime,endTime,deviceMac=[]):
        #http://open.zhimatech.com/api/v3/zhimind/entered_customer_count
        api_name = 'entered_customer_count'
        params = self.get_params_from_method(inspect.getargvalues(inspect.currentframe()))
            
        ws_result = self.getResponse(url=self.base+'/'+api_name, detailMap=params)
        return ws_result
    def touched_customer_count(self,startTime,endTime,deviceMac=[]):
        #http://open.zhimatech.com/api/v3/zhimind/touched_customer_count
        api_name = 'touched_customer_count'
        params = self.get_params_from_method(inspect.getargvalues(inspect.currentframe()))
        ws_result = self.getResponse(url=self.base+'/'+api_name, detailMap=params)
        return ws_result
    
    def customer_mac_info(self,startTime,endTime,deviceMac=[],mac=[]):
        # http://open.zhimatech.com/api/v3/zhimind/customer_mac_info
        api_name = 'customer_mac_info'
        params = self.get_params_from_method(inspect.getargvalues(inspect.currentframe()))
        ws_result = self.getResponse(url=self.base+'/'+api_name, detailMap=params)
        return ws_result
    
    
    def customer_stayed_distributing(self,startTime,endTime,deviceMac=[],duration=0):
        #http://open.zhimatech.com/api/v3/zhimind/customer_stayed_distributing
        api_name = 'customer_stayed_distributing'
        params = self.get_params_from_method(inspect.getargvalues(inspect.currentframe()))
        ws_result = self.getResponse(url=self.base+'/'+api_name, detailMap=params)
        return ws_result
    
    
    #实时接口
    def realtime_customers_rate(self,currentTime=None,group=None):
        '''1.    当前入店率'''
        api_name = 'realtime_customers_rate'
        params = self.get_params_from_method(inspect.getargvalues(inspect.currentframe()))
        ws_result = self.getResponse(url=self.base+'/'+api_name, detailMap=params)
        return ws_result
    
    def realtime_customers_count(self,currentTime=None,group=None):
        '''2.    当前入店数量'''
        api_name = 'realtime_customers_count'
        params = self.get_params_from_method(inspect.getargvalues(inspect.currentframe()))
        ws_result = self.getResponse(url=self.base+'/'+api_name, detailMap=params)
        return ws_result    
    
    def realtime_customers_type(self,currentTime=None,group=None):
        '''3.    新老顾客的数量'''
        api_name = 'realtime_customers_type'
        params = self.get_params_from_method(inspect.getargvalues(inspect.currentframe()))
        ws_result = self.getResponse(url=self.base+'/'+api_name, detailMap=params)
        return ws_result 
    
    def today_customers_count_hours(self,currentTime=None,group=None):
        '''4.    当天每小时数量统计'''
        api_name = 'today_customers_count_hours'
        params = self.get_params_from_method(inspect.getargvalues(inspect.currentframe()))
        if not params.has_key('StartTime'):
            params['StartTime'] = datetime.date.today().strftime('%Y-%m-%d') +' 00:00:00'
        if not params.has_key('EndTime'):
            params['EndTime'] = datetime.date.today().strftime('%Y-%m-%d') +' 23:59:59'
        ws_result = self.getResponse(url=self.base+'/'+api_name, detailMap=params)
        return ws_result 
    
    def realtime_people_count(self,currentTime=None,group=None):
        '''5.    当前客流量'''
        api_name = 'realtime_people_count'
        params = self.get_params_from_method(inspect.getargvalues(inspect.currentframe()))
        ws_result = self.getResponse(url=self.base+'/'+api_name, detailMap=params)
        return ws_result 


    
    
    def stats_ing_rate(self,startTime,endTime,group,groupType=4,Dimension=1):
        '''3.    入店率（趋势）'''
        api_name = 'statis_customer/stats_ing_rate'
        
        #token = md5.new(self.app_key+str(self.time)+self.secret_key).hexdigest()
        params = self.get_params_from_method(inspect.getargvalues(inspect.currentframe()))
        ws_result = self.getResponse(url=self.base+'/'+api_name, detailMap=params)
        return ws_result
    
    
    def stats_customer_count(self,startTime,endTime,group,groupType=4,Dimension=1,customerType=0):
        '''4.    入店量（趋势）'''
        api_name = 'statis_customer/stats_customer_count'
        params = self.get_params_from_method(inspect.getargvalues(inspect.currentframe()))
        ws_result = self.getResponse(url=self.base+'/'+api_name, detailMap=params)
        return ws_result
    
    def stats_people_flow(self,startTime,endTime,group,groupType=4,Dimension=1):
        '''5.    客流量（趋势）'''
        api_name = 'statis_customer/stats_people_flow'
        params = self.get_params_from_method(inspect.getargvalues(inspect.currentframe()))
        ws_result = self.getResponse(url=self.base+'/'+api_name, detailMap=params)
        return ws_result
    
    
    def customer_data_trend(self,startTime,endTime,group,groupType=4,Dimension=1,customerType=3):
        '''6.    顾客类型（趋势）'''
        api_name = 'statis_customer_type/customer_data_trend'
        params = self.get_params_from_method(inspect.getargvalues(inspect.currentframe()))
        ws_result = self.getResponse(url=self.base+'/'+api_name, detailMap=params)
        return ws_result
    
    def stats_visit_frequency_scatter(self,startTime,endTime,group,groupType=4,customerType=3):
        '''7.    到访次数分布'''
        api_name = 'statis_frequency/stats_visit_frequency_scatter'
        params = self.get_params_from_method(inspect.getargvalues(inspect.currentframe()))
        ws_result = self.getResponse(url=self.base+'/'+api_name, detailMap=params)
        return ws_result
    
    def duration_trend(self,startTime,endTime,group,groupType=4,customerType=3,Dimension=1):
        '''8.    驻店时长（趋势）'''
        api_name = 'statis_duration/duration_trend'
        params = self.get_params_from_method(inspect.getargvalues(inspect.currentframe()))
        ws_result = self.getResponse(url=self.base+'/'+api_name, detailMap=params)
        return ws_result
    
    def visit_cycle_trend(self,startTime,endTime,group,groupType=4,Dimension=1):
        '''9.    来访周期（趋势）'''
        api_name = 'statis_visit_cycle/visit_cycle_trend'
        params = self.get_params_from_method(inspect.getargvalues(inspect.currentframe()))
        ws_result = self.getResponse(url=self.base+'/'+api_name, detailMap=params)
        return ws_result
    
    
    
    def trend_rank_by_group(self,startTime=None,timeType=1,groupList=[],groupType=4,requestType=4,orderItem=3,orderType=1,pageNumber=1,currentPage=0):
        '''2.    趋势排行'''
        api_name = 'over_view/trend_rank_by_group'
        params = self.get_params_from_method(inspect.getargvalues(inspect.currentframe()))
        ws_result = self.getResponse(url=self.base+'/'+api_name, detailMap=params)
        return ws_result
        

    
    def stats_all_groups(self,group):
        '''1.    获取门店信息'''
        api_name = 'stats_all_groups'
        params = self.get_params_from_method(inspect.getargvalues(inspect.currentframe()))
        ws_result = self.getResponse(url=self.base+'/'+api_name, detailMap=params)
        return ws_result
    
    def get_people_unique_count(self,startTime=None,endTime=None,group=None,groupType=4,dimension=0):
        u'''10.    客流人数（趋势）'''
        api_name= 'people/get_people_unique_count'
        params = self.get_params_from_method(inspect.getargvalues(inspect.currentframe()))
        ws_result = self.getResponse(url=self.base+'/'+api_name, detailMap=params)
        return ws_result
    
    
    def get_walkby_count(self,startTime=None,endTime=None,group=None,groupType=4,dimension=0):
        u'''11.    路过客流人次（趋势）'''
        api_name = 'people/get_walkby_count'
        params = self.get_params_from_method(inspect.getargvalues(inspect.currentframe()))
        ws_result = self.getResponse(url=self.base+'/'+api_name, detailMap=params)
        return ws_result
    
    
    def get_new_customer_flow_rate(self,startTime=None,endTime=None,group=None,groupType=4,dimension=0):
        u'''12.    新客流入店率（趋势）'''
    
        api_name = 'customer/get_new_customer_flow_rate'
        params = self.get_params_from_method(inspect.getargvalues(inspect.currentframe()))
        ws_result = self.getResponse(url=self.base+'/'+api_name, detailMap=params)
        return ws_result
    
    
    def get_old_customer_flow_rate(self,startTime=None,endTime=None,group=None,groupType=4,dimension=0):
        u'''13.    重复客流入店率（趋势）'''
    
        api_name = 'customer/get_old_customer_flow_rate'
        params = self.get_params_from_method(inspect.getargvalues(inspect.currentframe()))
        ws_result = self.getResponse(url=self.base+'/'+api_name, detailMap=params)
        return ws_result
    
    
    def get_deep_visit_rate(self,startTime=None,endTime=None,customerType=0,group=None,groupType=4,dimension=0):
        u'''14.    某类型顾客深访率（趋势）'''
    
        api_name = 'visit/get_deep_visit_rate'
        params = self.get_params_from_method(inspect.getargvalues(inspect.currentframe()))
        ws_result = self.getResponse(url=self.base+'/'+api_name, detailMap=params)
        return ws_result
    
    
    def get_jump_out_visit_rate(self,startTime=None,endTime=None,customerType=0,group=None,groupType=4,dimension=0):
        u'''15.    某类型顾客跳出率（趋势）'''
    
        api_name = 'visit/get_jump_out_visit_rate'
        params = self.get_params_from_method(inspect.getargvalues(inspect.currentframe()))
        ws_result = self.getResponse(url=self.base+'/'+api_name, detailMap=params)
        return ws_result
    
    
    def get_visit_cycle_by_activity(self,startTime=None,endTime=None,group=None,groupType=4,dimension=0):
        u'''16.    老顾客中的各活跃度类型顾客平均来访周期'''
    
        api_name = 'visit/get_visit_cycle_by_activity'
        params = self.get_params_from_method(inspect.getargvalues(inspect.currentframe()))
        ws_result = self.getResponse(url=self.base+'/'+api_name, detailMap=params)
        return ws_result
    
    
    def main(self,timeType=1,groupType=4,shop_group=None,city_group=None,prov_group=None,comp_group=None,customerType=0):
        
        dimension = timeType
        if groupType == 4:
            groupList = [shop_group]
            
        elif groupType == 2:
            groupList = [city_group]
        elif groupType == 1:
            groupList = [prov_group]
        else:
            groupList = [comp_group]
        group = groupList[0]
        if timeType == 1:
            startTime = endTime ="2015-09-25"
        elif timeType == 2:
            startTime = '2015-09-21'
            endTime = '2015-09-27'
        elif timeType == 3:
            startTime = '2015-09-01'
            endTime ='2015-09-30'
        else:
            startTime = endTime ="2015-11-03"
            
        
        currentTime = datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')
        currentTime = '2015-11-06 14:16:55'
           
        if api_num == '2.1':
            print self.realtime_customers_rate(currentTime, group)
        if api_num == '2.2':
            print self.realtime_customers_count(currentTime, group)
        if api_num == '2.3':
            print self.realtime_customers_type(currentTime, group)     
        
        if api_num == '2.4':
            print self.today_customers_count_hours(currentTime, group)
        if api_num == '2.5':
            print self.realtime_people_count(currentTime, group)
        
        
        if api_num == '3.8':
            print self.duration_trend(startTime, endTime, group, groupType, customerType, dimension)
        
        
        if api_num == '3.10':
            print self.get_people_unique_count(startTime, endTime, group, groupType, dimension)
        if api_num == '3.11':
            print self.get_walkby_count(startTime, endTime, group, groupType, dimension)
        if api_num == '3.12':
            print self.get_new_customer_flow_rate(startTime, endTime, group, groupType, dimension)
        
        if api_num == '3.13':
            print self.get_old_customer_flow_rate(startTime, endTime, group, groupType, dimension)
        
        
        if api_num == '3.14':
            print self.get_deep_visit_rate(startTime, endTime, customerType, group, groupType, dimension)
        if api_num == '3.15':
            print self.get_jump_out_visit_rate(startTime, endTime, customerType, group, groupType, dimension)
        if api_num == '3.16':
            print self.get_visit_cycle_by_activity(startTime, endTime, group, groupType, dimension)
        
    
    
if __name__=='__main__':
    version = 'v4'
    if version == 'v3':
        base = 'http://192.168.1.208:38080/zm-ws-3.0/api/v3'
    else:
        base = 'http://open.zhimatech.com/api/retail/v3'
        #base = 'http://192.168.1.208:38080/zm-ws-4.0/api/v3'
    myVerifyZhimindWSV4Data = VerifyZhimindWSV4Data(base=base,version=version)
    
    logging.basicConfig(level = logging.DEBUG)
    shop_group = 32012194
    city_group = 32010224
    prov_group = 32010223
    comp_group = 32010222
    groupType = 4
    
    
    
    timeType = 2
    requestType = groupType
    xType = 1
    yType = 2
    
    customerType = 0
    
    api_num = '3.16'
    
    for timeType in [1,2,3]:
        myVerifyZhimindWSV4Data.main(timeType, groupType, shop_group, city_group, prov_group, comp_group,customerType)
    
    
